/*
 * @Author: HZK
 * @Date: 2020-11-18 16:22:45
 * @LastEditTime: 2020-12-01 16:25:23
 * @LastEditors: hanfengmi
 * @Description: 封装请求
 */
import { extend } from 'umi-request';

/**
 * 异常处理程序
 */
const errorHandler = (status, url) => {
  console.log(`error_status:${status};error_url:${url}`)
};

/**
 * 成功处理errcode程序
 */
const errcodeFn = (code, url)=>{
  console.log(`error_status:${code};error_url:${url}`)
}

/**
 * 处理请求url
 */
const apiUrl = val => {
  if(process.env.prod !== 'prod'){
    return `/api/${val}`;
  }else {
    return `${ window.location.origin }/${val}`;
  }
};

/**
 * 配置request请求时的默认参数
 */
const request = extend({
  mode:'cors',
  timeout: 20000,
  // credentials: 'include', // 默认请求是否带上cookie 
});

request.interceptors.request.use(async (url, options) => {
  // 此处可二次封装请求头
  return (
    {
      url:apiUrl(url),
      options,
    }
  );
})

request.interceptors.response.use(async (response) => {
  if(response.status === 200){ // 成功请求
    const data = await response.clone().json();
    console.log(data)
    if(data.Success !== true){
      errcodeFn(data.Message, response.url)
      return response
    }
    if(data.errcode !==200){
      errcodeFn(data.errcode, response.url)
      return response;
    }
    return response;
  }else { // 接口报错
    try{
      // java接口使用
      // const data = await response.clone().json();
      errorHandler(response.status,response.url)
    }catch{// php接口使用
      errorHandler(response.status,response.url)
    }
  }
})

export default request;
